package com.jackrain.nea.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Lucky dog on 2016/7/27.
 */
public class ShiroSessionUtil {

    /**
     *
     * @param request ShiroHttpSession
     * @return
     */
    public static HttpServletRequest getHttpServletRequest(ServletRequest request){
        ServletRequestWrapper servletRequestWrapper = (ServletRequestWrapper)request;
        return (HttpServletRequest)servletRequestWrapper;
    }

    /**
     *
     * @param request ShiroHttpSession
     * @return
     */
    public static HttpSession getHttpSession(ServletRequest request){
        ServletRequestWrapper servletRequestWrapper = (ServletRequestWrapper)request;
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequestWrapper.getRequest();
        return httpServletRequest.getSession();
    }

    /**
     *
     * @param request ShiroHttpSession
     * @param name attribute name
     * @param value attribute name
     */
    public static void setAttribute(ServletRequest request,String name,Object value){
        ServletRequestWrapper servletRequestWrapper = (ServletRequestWrapper)request;
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequestWrapper.getRequest();
        httpServletRequest.getSession().setAttribute(name,value);
    }

    /**
     *
     * @param request ShiroHttpSession
     * @param name
     * @return
     */
    public static Object getAttribute(ServletRequest request,String name){
        ServletRequestWrapper servletRequestWrapper = (ServletRequestWrapper)request;
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequestWrapper.getRequest();
        return httpServletRequest.getSession().getAttribute(name);
    }

    public static Session getSession(){
        return SecurityUtils.getSubject().getSession();
    }


    public static Object getAttribute(String name){
        return SecurityUtils.getSubject().getSession().getAttribute(name);
    }

    public static  void setAttribute(String name,Object value){
         SecurityUtils.getSubject().getSession().setAttribute(name,value);
    }

    public static  void removeAttribute(String name){
        SecurityUtils.getSubject().getSession().removeAttribute(name);
    }

    public static boolean isLogin(){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isRemembered()){
            subject.getSession().setAttribute("user",subject.getPrincipal());
        }
        return subject.isAuthenticated()||subject.isRemembered();
    }

}
